

import {AppSendEventCallback} from "./i_app_send_event";
import IAppSendEvent from "./i_app_send_event";
import rpc from "@ohos.rpc";

export default class AppSendEventStub extends rpc.RemoteObject implements IAppSendEvent {
    constructor(des: string) {
        super(des);
    }
    
    async onRemoteMessageRequest(code: number, data:rpc.MessageSequence, reply:rpc.MessageSequence, option:rpc.MessageOption): Promise<boolean> {
        let localDescriptor = this.getDescriptor();
        let remoteDescriptor = data.readInterfaceToken();
        if (localDescriptor != remoteDescriptor) {
            console.log("invalid interfaceToken");
            return false;
        }
        console.log("onRemoteMessageRequest called, code = " + code);
        switch(code) {
            case AppSendEventStub.COMMAND_APP_SEND_EVENT: {
                let dataVar = new Map();
                let dataVarSize = data.readInt();
                for (let i = 0; i < dataVarSize; ++i) {
                    let key = data.readString();
                    let value = data.readString();
                    dataVar.set(key, value);
                }
                let promise = new Promise<void>((resolve,reject) => { 
                    this.appSendEvent(dataVar, (errCode,returnValue) => {
                        reply.writeInt(errCode);
                        reply.writeString(returnValue);
                        resolve();
                    });
                });
                await promise;
                return true;
            }
            default: {
                console.log("invalid request code" + code);
                break;
            }
        }
        return false;
    }

    appSendEvent(data: Map<string, string>, callback: AppSendEventCallback): void{}

    static readonly COMMAND_APP_SEND_EVENT = 1;
}

